package com.yue.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;

public class BaseDAO<T> {
    QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
    Class<T> type;

    public BaseDAO() {
        Class<? extends BaseDAO> clazz = this.getClass();
        ParameterizedType pt = (ParameterizedType) clazz.getGenericSuperclass();
        Type[] types = pt.getActualTypeArguments();
        type = (Class<T>) types[0];
    }

    //增删改方法
    public int update(String sql, Object... params) throws SQLException {
        int row = qr.update(sql, params);
        return row;
    }

    //查询一个
    public T getbean(String sql, Object... params) throws SQLException {
        T t = qr.query(sql, new BeanHandler<T>(type), params);
        return t;
    }

    //查多个
    public List<T> geTListbean(String sql, Object... params) throws SQLException {
        List<T> list = qr.query(sql, new BeanListHandler<T>(type), params);
        return list;
    }

    //查数
    public Object count(String sql, Object... params) throws SQLException {
        Object o = qr.query(sql, new ScalarHandler<>(), params);
        return o;
    }


}
